<template>
    <view class="content">
		
        <view class="index-content" >
            <image class="main-bg" :src="myBackImage" mode="aspectFill"></image>
			<view class="title">我的</view>
            <view class="top f-r-s box-s" >
                <view class="top-pic" @click="editModal=true && isLogin">
					<image  :src="userinfo.avatar&&userinfo.avatar!=''?userinfo.avatar:defHead" ></image>
				</view>
				<view class="top-right">
					<view class="nickname" v-if="isLogin">{{userinfo.nickName}}</view>
					<view class="f-r-s vip" >
						<image :src="vipStatusIcon" mode="heightFix" style="height: 32rpx;"></image>
						<!-- <uni-icons  type="vip" size="24" :color="userinfo.isVip?themeColor:'#999' " ></uni-icons> -->
						<text v-if="!userinfo.isVip||!isLogin ">未开通VIP</text>
						<text v-if=" userinfo.isVip && isLogin">VIP到期时间 {{userinfo.memberExpireDate?$parseTime(userinfo.memberExpireDate,'{y}年{m}月{d}日'):''}}</text>
					</view>
				</view>
            </view>
            <view class="join"  @click="open_url('/pages/invite/friend',{})">
				<image :src="advertisementBarPicture" mode="aspectFill"></image>
			</view>

           <view class="form">
                <view class="form-item">
                    <view class="label">昵称</view>
					<view class="right" >
						<view v-if="isLogin">{{userinfo.nickName}}</view>
					</view>
                   
                </view>
                <view class="form-item">
                    <view class="label">手机号</view>
					<view class="right">
						<view v-if="isLogin">{{userinfo.phoneNumber}}</view>
					</view>
                </view>
                <view class="form-item" @click="tovip">
                    <view class="label">VIP</view>
					<view class="right" >
						<view class="right-btn bggradient">{{userinfo.isVip?'续费会员':'开通会员'}}</view>
						<image src="../../static/image/right_grey_icon.png"></image>
					</view>
                    
                </view>
				<view class="form-item" @click="open_url('/pages/index/follow',{showBtntype:2})">
				    <view class="label">我的关注</view>
					<view class="right" >
						<view></view>
						<image src="../../static/image/right_grey_icon.png"></image>
					</view>
				</view>
				<view class="form-item" @click="open_url('/pages/invite/index',{})">
				    <view class="label">邀新用户</view>
					<view class="right" >
						<view class="right-btn bggradient">邀新用户</view>
						<image src="../../static/image/right_grey_icon.png"></image>
					</view>
				    
				</view>
				<view class="form-item" @click="tovipdetailWechat('/pages/index/wechat',{})">
				    <view class="label">会员交流群</view>
					<view class="right" >
						<view></view>
						<image src="../../static/image/right_grey_icon.png"></image>
					</view>
				</view>
				
            </view>
        </view>
		<!-- 登录 -->
		<view class="login-black" v-if="showLoginDialog">
			<view class="login-white" >
				<view v-if="loginStep" class="box">
					<view class="f-r-c title">请先授权登录</view>
					<view class="checkbox f-r-c" >
					    <checkbox-group @change="isCheckedChange" :disabled="agreeXy" >
					        <label style="font-size: 26rpx;color: #666;"  class="f-r-s">
					            <checkbox :checked="agreeXy" :color="themeColor" :disabled="agreeXy" ></checkbox>
					            我已阅读并同意
					            <span  @click="open_protocol()" :style="{'color':themeColor,}">&nbsp;《注册协议》《隐私保护政策》</span>
					        </label>
					        
					    </checkbox-group>
					   
					</view>
					<view class="foot">
						<view class="f-r-c btn "  :style="{'color':themeColor,'background':themeColor+'20'}" @click="cancelLogin">取消</view>
						<view class="f-r-c btn"  :style="{'color':'#fff','background':themeColor}" @click="onLogin" >确认</view>
					</view>
				</view>
				
				<view v-if="phoneStep" class="box">
					<view class="f-r-c title">手机号快捷登录</view>
					<view class="f-r-c checkbox">
						<text >
							为了更好的为您服务，在官方网站或者 APP 登录使用时，同步用户信息，需要您授权手机号
						</text>
					</view>
					<view class="foot">
						<view class="f-r-c btn "  :style="{'color':themeColor,'background':themeColor+'20'}" @click="cancelPhone">取消</view>
						<button class="f-r-c btn" :style="{'color':'#fff','background':themeColor}" hover-class="none" type='primary' open-type="getPhoneNumber" @getphonenumber="submitPhone" >确认</button>
					</view>
				</view>
				
			</view>
		</view>
		
		<!-- 获取用户名和昵称 -->
		<editUserModal :isShow="editModal" @closeEdit="closeEdit" @editSuccess="editSuccess"></editUserModal>
		
	</view>
</template>

<script>
import editUserModal from '@/components/xghc-editUserModal/index.vue';
export default {
    data() {
        return {
			myBackImage:'',
			advertisementBarPicture:'',
			vipStatusIcon:'',
            isLogin:false,//是否登录
			defHead: require('@/static/image/def_avatar.png'),
            userinfo:{
				avatar:'',
				nickName:'',
				userId:null,
				userName:'',
				userDesc:'',
				phoneNumber:'',
				memberId:null,//会员id
				memberExpireDate:'',//会员到期时间
				referralCode:'',//会员推广码
				disable:0,//会员状态（0普通, 1会员, 2过期）
				isVip:false,//是否VIP 


			},
			
			showLoginDialog:false,
			//同意协议
			agreeXy:false,
			loginStep:true, //显示登录按钮
			phoneStep:false, //显示授权手机号按钮
			code:'',
			loadingIcon:false,//避免重复点击
			editModal:false, //授权昵称和头像
			useriv:'',
            userencryptedData:'',
			referralCode:'',//推给我得用户得推广码
			 isChecked: false,
        }
    },
	components:{
		editUserModal,
	},
    onLoad() {
		let referralCode = uni.getStorageSync("referralCode");
		console.log("推给我得用户得推广码",referralCode);
		this.referralCode=referralCode&&referralCode!=undefined?referralCode:'';
		this.myBackImage=this.$prefix(uni.getStorageSync("configData").myBackImage);
		this.advertisementBarPicture=this.$prefix(uni.getStorageSync("configData").advertisementBarPicture);
		this.vipStatusIcon=this.$prefix(uni.getStorageSync("configData").vipStatusIcon);
    },
	computed: {
		themeColor() {
			return this.$themeColor;
		},
	},
    onShow() {
		this.getUserInfo();
		this.autoOpenEditUserModial();
    },
    methods:{
		// 检测用户是否修改过头像昵称，没有修改过则弹出让用户修改
		autoOpenEditUserModial() {
			if (this.isLogin) {
				// 已登录，则检查是否需要修改昵称头像信息
				console.log('已登录，则检查是否需要修改昵称头像信息 ');
				if (this.userinfo.nickName == ("微信用户" + this.userinfo.userId)) {
					// 需要修改
					this.editModal = true;
				}
			}
		},
		isCheckedChange(e){
		     this.agreeXy=true;
		},
		//查看用户协议
		open_protocol: function() {
			this.agreeXy=true;
			uni.navigateTo({
				url: '/pages/main/UserAgreement',
			});
		},
		//修改头像 昵称
		editSuccess(data) {
			this.editModal = false;
			console.log(data);
			this.userinfo.avatar=data.avatar;
			this.userinfo.nickName=data.nickName;
		},
		//关闭修改头像昵称
		closeEdit() {
			this.editModal = false;
		},
		//开通会员
		tovip(){
			if(this.isLogin){
				uni.navigateTo({
					url:'/pages/main/buyVip',
				})
			}else{
				uni.showToast({
					title:'请登录后体验完整功能',
					icon:'none',
				})
			}
		   
		},
		//获取用户信息，判断是否登录并给出对应提示
		//跳转
		tovipdetailWechat(url,param){
			if(!this.isLogin){
				uni.showToast({
					title:'请登录后体验完整功能',
					icon:'none',
				})
				return false;
			}
			if(!this.userinfo.isVip){
				uni.showToast({
					title:'扫描二维码联系客服体验完整功能!',
					icon:'none',
				})
				let that = this;
				setTimeout(function() {
					console.log('1秒的定时器');
					// 客服二维码
					let codeFilePath = uni.getStorageSync('configData').adminWxQrcode;
					let url=that.$prefix(codeFilePath);
					let list=[];
					list.push(url);
					uni.previewImage({
					     urls: list, //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了     		
					     success: function(res) { 
					     },
					     complete: function(res) {
					        
					     },
					 });
				}, 1500);
			}else{
				this.open_url(url,param);
			}
		},
		//邀请好友//我的关注//邀新用户//会员交流群
		open_url(url,param){
			if(this.userinfo.isVip){
				if (JSON.stringify(param) != "{}") {
					url += '?';
					for (let k in param) {
						url += k + '=' + param[k] + '&';
					}
					url = url.substring(0, url.length - 1);
				}
				
				uni.navigateTo({
					url: url,
					fail: (e) => {
						console.info(e)
					}
				});
			}else{
				let that=this;
				uni.showModal({
					title:'温馨提示',
					content:'请购买VIP会员后查看',
					cancelText:'取消',
					confirmText:'购买',
					success: function (res) {
						if (res.confirm) {
							that.tovip();
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
					
				})
			}
			
		},
		getUserInfo(){
		    let opts = {
		    	url: '/wx/getUserInfo',
		    	method: 'get'
		    };
		    let _self=this;
		    _self.$http(opts,{}).then(res => {
				console.log(res);
		    	if(res.code==200){
		            _self.userinfo=res.data;
		            uni.setStorageSync('userinfo',res.data);
					_self.isLogin=true;
		    	}else{
					_self.isLogin=false;
					_self.open();
					console.log("未登录");
				}
		    }) 
		},
		getCode(){
		    wx.login({
		        success:(res) => {
		            this.code = res.code;
		        }
		    })
		},
		onLogin() {
			console.log("this.agreeXy",this.agreeXy);
			if(!this.agreeXy){
				uni.showToast({
					title:'需要阅读并同意注册协议和隐私保护政策',
					icon:'none',
				})
				return false;
			}
			
			this.getCode();
			if(this.loadingIcon){
				return false;
			}
			this.loadingIcon=true;  //请求中
			let that=this;
			uni.getUserProfile({
				desc: "weixin",
				success: (res1) => {
			        if(res1.errMsg=='getUserProfile:ok'){
						that.useriv=res1.iv;
						that.userencryptedData=res1.encryptedData;
						
			             let opts = {
			                url: '/wx/login',//先判断是否是新用户 
			                method: 'POST'
			             };
						
			             let param = {
			                 encryptedData:'',  //用户加密信息 或昵称头像
			                 iv:'',
			                 code:that.code,	
							 signature:res1.iv,
							 rawData:res1.encryptedData,
							 superReferralCode:this.referralCode,
							 
			             };
			             that.$http(opts, param).then(res3 => {
			                 if(res3.code=='200'){
								 //如果是老用户 返回token和手机号 ，不是老用户 继续授权手机号登录
								let token=res3.token;
								if(token&&token!=''){
									uni.setStorageSync('token',res3.token);
									

									that.showLoginDialog=false;
									this.loadingIcon=false;
									
									uni.showToast({
										title:'登录成功',
										icon:'none',
									})
									that.getUserInfo();
									
								}else{
									this.loadingIcon=false;
									that.loginStep=false;
									that.phoneStep=true;
								}
								
								
								
			                
			                 }else{
			                    uni.showToast({
			                        title:res3.msg,
			                        icon:'none'
			                    })
			                 }
			             })
			                     
			        }
			        
				},
				fail: (err) => {
					console.log(err)
				}
			})
		},
		//打开登录弹框
		open(){
        	this.showLoginDialog=true;
        },
		//取消登录
        cancelLogin(){
        	this.showLoginDialog=false;
        },
        
        //取消授权手机号
        cancelPhone(){
        	this.loginStep=true;
        	this.phoneStep=false;
            this.showLoginDialog=false;
        },
        //授权授权 获取手机号 code 用于登录
        submitPhone(e) {
			if(this.loadingIcon){
				return false;
			}
			this.loadingIcon=true;
			if (e.detail.errMsg == "getPhoneNumber:ok") {
				// console.log("手机号授权详情",e.detail);
				
			    let res1=e.detail;
				let that=this;
			    uni.login({
			         provider: 'weixin',
			         success: (res2) => {
			             let opts = {
			                url: '/wx/login',
			                method: 'POST'
			             };
			             let param = {
			                 encryptedData:res1.encryptedData,
			                 iv:res1.iv,
			                 code:res2.code,	
							 signature:that.useriv,
							 rawData:that.userencryptedData,
							 superReferralCode:this.referralCode,
			             };
						 
			             that.$http(opts, param).then(res3 => {
			                 
			                 if(res3.code=='200'){
			                   uni.setStorageSync('token',res3.token);
			                   that.showLoginDialog=false;
							   that.loadingIcon=false;
			                   uni.showToast({
			                   	title:'登录成功',
			                   	icon:'none',
			                   })
							   that.getUserInfo();
			                    
			                 }else{
			                    uni.showToast({
			                        title:res3.msg,
			                        icon:'none'
			                    })
			                 }
			             })
			             
			         },
			    });
			    
			} else {
			    uni.showToast({
			        title:'手机号授权失败',
			        icon:'none',
			    })
			}
            
        },
		
       
    }
    
}


</script>

<style scoped lang="less">
button{
        border:0;
        -webkit-tap-highlight-color: transparent;
        background-color:transparent;
//         // border-radius:50%;
        box-sizing: border-box;
//         color: #000;
        cursor: pointer;
//         display: block;
       border-radius: 20rpx;
       font-size: 33rpx;
       font-weight: 500;
       text-align: center;
        line-height:0;
        margin-left: 0;
        margin-right: 0;
        overflow: hidden;
        padding-left: 0;
        padding-right: 0;
        position: relative;
        text-decoration: none;
}
button::after{
     border:0;
}

.content{
	.login-black{
		width: 100vw;
		height: 100vh;
		background: rgba(0,0,0,0.4);
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		z-index: 200;
		.login-white{
			position: absolute;
			bottom: 0;
			left: 0;
			right: 0;
			background: #fff;
			border-radius: 20rpx 20rpx 0 0;
			.box{
				overflow: hidden;
				.title{
					text-align: center;
					font-size: 40rpx;
					color: #000;
					font-weight: 500;
					margin-bottom: 20rpx;
					margin-top: 60rpx;
				}
				.checkbox{
					margin: 0 60rpx 60rpx ;
					height: 70rpx;
					label{
						font-size: 26rpx;
						color: #bbb;
						text-align: center;
					}
					text{
						font-size: 26rpx;
						color: #bbb;
						text-align: center;
					}
					
					
				}
				.foot{
					margin-bottom: 20rpx;
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: space-around;
					.btn{
						width: 240rpx;
						height: 80rpx;
						border-radius: 20rpx;
						font-size: 33rpx;
						font-weight: 500;
						text-align: center;
						
					}
				}
						
			}
			
		}
	}
    
	.index-content{
		position: relative;
		top: 140rpx;
		box-sizing: border-box;
		z-index: 100;

		
        .main-bg{
            width: 100vw;
            height:400rpx;
            background-size: cover;
            position: fixed;
            top:0;
            left: 0;
            right: 0;
            bottom: 0;
            z-index: -1;
			// border-radius: 0 0 30% 40%;
            
        
        }
		.title{
			text-align: center;
			font-size: 40rpx;
			color: #fff;
		   font-weight: 500;
		   margin-bottom: 80rpx;
		}
        .top{
			
			width: 100%;
			height: 200rpx;
			padding: 20rpx;
			box-sizing: border-box;
			background: #fff;
            overflow: hidden;
			border-radius: 20rpx;
			.top-pic{
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
				margin-right: 20rpx;
				overflow: hidden;
				image{
					width: 100%;
					height: 100%;
					background-size: 100% 100%;
				}
				
			}
			.top-right{
				.nickname{
					font-size: 38rpx;
					color: #000;
					height: 60rpx;
					line-height: 60rpx;
					text-align: left;
					font-weight: 500;
					
					
				}
				.vip{
					image{
						width: 50rpx;
						height: 50rpx;
					}
					text{
						color: #666;
						font-weight: 400;
						margin-left: 10rpx;
						font-size: 26rpx;
					}
				}
			}
            
           
        }
		.join{
			margin:  30rpx 0;
			height: 170rpx;
			border-radius: 100rpx;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
				background-size: 100%;
			}
			
		}
        
        
        
        
        .form{
           
            .form-item{
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                border-bottom: 1rpx #eee solid;
				height: 100rpx;
                
                
                .label{
                    flex: 1;
                    height: 48rpx;
                     opacity: 1;
                     color: #303336ff;
                     font-size: 30rpx;
                     font-weight: 400;
                     font-family: "PingFang SC";
                     text-align: left;
                     line-height: 48rpx;
                     
                }
                image{
                    width: 32rpx;
                    height: 32rpx;
					margin: 0 0 0 10rpx;
                }
				.right{
					display: flex;
					flex-direction: row;
					align-items: center;
					justify-content: flex-end;
					view{
						color: #999;
						font-size: 28rpx;
						text-align:right;
						line-height: 48rpx;
						height: 48rpx;
					}
					.right-btn{
						line-height: 48rpx;
						height: 48rpx;
						width: 170rpx;
						color: #fff;
						font-size: 28rpx;
						text-align:center;
						border-radius: 30rpx;
					}
				}
                
                
            }
            
            
            
        }
       
    }
    
}
</style>